﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

using EZCRS.HCMS.Bll.baseinfo;
using EZCRS.HCMS.Entity;

using GFrame.Shadow;
using GFrame.Shadow.Search;
using System.Data;

namespace EZCRS.HCMS.Bll.AIR
{
    public class AIR
    {
        /// <summary>
        /// 获取AIR表记录
        /// </summary>
        /// <param name="PID">酒店ID</param>
        /// <param name="Level">计划级别</param>
        /// <param name="RoomCode">房型代码</param>
        /// <param name="Year">年份</param>
        /// <returns></returns>
        private List<HCRS_AIR> getRoomLevelAIR(int PID,  string RoomCode, int Year)
        {
            BllHCRS_AIR bll = new BllHCRS_AIR();

            string strWhere = "property_id =" + PID.ToString() + " AND level = 'R' AND RoomCode = '"
                + RoomCode + "' AND Year = " + Year.ToString();


            return bll.getall(strWhere);

        }

        /// <summary>
        /// 获取计划级别AIR记录
        /// </summary>
        /// <param name="PID"></param>
        /// <param name="RoomCode">st</param>
        /// <param name="PlanCode">st-bar</param>
        /// <param name="Year"></param>
        /// <returns></returns>
        private List<HCRS_AIR> getPlanLevelAIR(int PID, string RoomCode, string PlanCode, int Year)
        {
            BllHCRS_AIR bll = new BllHCRS_AIR();

            string strWhere = "property_id =" + PID + " AND level = 'L' AND RoomCode = '"
                + RoomCode + "' AND PlanCode = '" + PlanCode + "' AND Year = " + Year.ToString();

            return bll.getall(strWhere);

        }

        /// <summary>
        /// 房型级价格保存
        /// </summary>
        /// <param name="Inventory"></param>
        /// <param name="Min"></param>
        /// <param name="Max"></param>
        /// <param name="AdvanceHour"></param>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        /// <param name="DayOfWeek"></param>
        /// <param name="Quota"></param>
        /// <returns></returns>
        public bool SaveRoomLevel(int PID, string [] RoomCodes, int Inventory, int Min, int Max, int AdvanceHour, string State,
            DateTime StartDate, DateTime EndDate, int[] DayOfWeek, Hashtable Quota)
        {
            if (StartDate > EndDate) return false;

            DateTime dtStartDate = Convert.ToDateTime(StartDate.ToString()); //创建一个原始开始日期

            BllHCRS_AIR bll = new BllHCRS_AIR();

            int iYears = EndDate.Year - StartDate.Year;

            for (int i = 0; i <= iYears; i++)
            {

                #region 按年分隔日期

                DateTime dtStart = StartDate;
                DateTime dtEnd;

                if (iYears == 0)
                {
                    //同一年
                    dtEnd = EndDate;
                }
                else if (iYears == i)
                {
                    //最后一年

                    if (iYears >= 1)
                        dtStart = Convert.ToDateTime(dtStart.Year.ToString() + "-1-1");

                    dtEnd = EndDate;
                }
                else
                {
                    if (i > 0)
                        dtStart = Convert.ToDateTime(dtStart.Year.ToString() + "-1-1");

                    //设置成本年最后一天
                    dtEnd = Convert.ToDateTime(StartDate.AddYears(1).Year.ToString() + "-1-1").AddDays(-1);
                }

                #endregion

                #region 房型循环

                foreach (string strRoomCode in RoomCodes)
                {

                    HotelAIProvider ai = new HotelAIProvider();

                    //先从数据库读取对象

                    HCRS_AIR air;

                    List<HCRS_AIR> airData = getRoomLevelAIR(PID, strRoomCode, StartDate.Year);

                    if (airData.Count > 0)
                    {
                        air = airData[0];

                        //为转换器加载数据

                        ai.Load(air);

                    }
                    else
                        air = new HCRS_AIR();


                    //将数据转换器内的数据更新
                    ai.Create(dtStart, dtEnd, DayOfWeek, Inventory, State,
                        Min, Max, AdvanceHour, string.Empty, string.Empty);

                    //更新实体类对象
                    air.PlanCode = "";
                    air.RoomCode = strRoomCode;
                    air.Property_id = PID;
                    air.Year = ai.Year;
                    air.Level = "R";

                    air.Source = "DEFAULT";

                    #region 数据转换

                    //房型房量数据转换
                    air.January_AI = ai.ConvertToBinaryData(1);
                    air.February_AI = ai.ConvertToBinaryData(2);
                    air.March_AI = ai.ConvertToBinaryData(3);
                    air.April_AI = ai.ConvertToBinaryData(4);
                    air.May_AI = ai.ConvertToBinaryData(5);
                    air.June_AI = ai.ConvertToBinaryData(6);
                    air.July_AI = ai.ConvertToBinaryData(7);
                    air.August_AI = ai.ConvertToBinaryData(8);
                    air.September_AI = ai.ConvertToBinaryData(9);
                    air.October_AI = ai.ConvertToBinaryData(10);
                    air.November_AI = ai.ConvertToBinaryData(11);
                    air.December_AI = ai.ConvertToBinaryData(12);

                    byte[] bEmpty = new byte[1];

                    air.January_R = bEmpty;
                    air.February_R = bEmpty;
                    air.March_R = bEmpty;
                    air.April_R = bEmpty;
                    air.May_R = bEmpty;
                    air.June_R = bEmpty;
                    air.July_R = bEmpty;
                    air.August_R = bEmpty;
                    air.September_R = bEmpty;
                    air.October_R = bEmpty;
                    air.November_R = bEmpty;
                    air.December_R = bEmpty;


                    #endregion

                    //写入数据库
                    bool b = bll.insertorupdate(air);

                    if (!b)
                        return false;

                    #region 写入计划级的AI...

                    BllRatePlan rateplan = new BllRatePlan();


                    HCRS_InventoryPlan invObj = new HCRS_InventoryPlan(); //房量配额设定记录表实体

                    Shadow<HCRS_InventoryPlan> shadow = new Shadow<HCRS_InventoryPlan>(invObj); //ORM对象

                    foreach (string key in Quota.Keys)
                    {
                        double fInv = Inventory * double.Parse(Quota[key].ToString()) * .01;

                        int iInv = (int)fInv;

                        if (iInv > 0)
                        {
                            //检查计划代码是否存在，没有需要新建,eq:ST-BAR

                            string strRatePlan = strRoomCode + "-" + key;

                            List<HCRS_Plan> planlst = rateplan.getPlan(PID, strRatePlan, 0);

                            #region 无此价格计划，需要创建

                            if (planlst == null || planlst.Count == 0)
                            {

                                HCRS_Plan newplan = new HCRS_Plan();

                                newplan.available = 1;
                                newplan.LanguageType = 0;
                                newplan.Pid = PID;
                                newplan.PlanCode = strRatePlan;
                                newplan.PlanName = strRatePlan;
                                newplan.RoomCode = strRoomCode;
                                newplan.updatetime = DateTime.Now;

                                b = rateplan.Add(newplan);

                                if (!b) return false;
                            }

                            #endregion

                            #region 写入AI表

                            HotelAIProvider planAI = new HotelAIProvider();
                            HotelRateProvider planRate = new HotelRateProvider();

                            List<HCRS_AIR> airPlanData = getPlanLevelAIR(PID, strRoomCode, key, StartDate.Year);

                            HCRS_AIR airObj;

                            if (airPlanData.Count > 0)
                            {
                                airObj = airPlanData[0];

                                //为转换器加载数据

                                planAI.Load(airObj);

                            }
                            else
                            {
                                airObj = new HCRS_AIR();

                                planRate.Create(dtStart, dtEnd, DayOfWeek, 0, 0, 0, 0, 0, false, 0, 0);

                                airObj.January_R = planRate.ConvertToBinaryData(1);
                                airObj.February_R = planRate.ConvertToBinaryData(2);
                                airObj.March_R = planRate.ConvertToBinaryData(3);
                                airObj.April_R = planRate.ConvertToBinaryData(4);
                                airObj.May_R = planRate.ConvertToBinaryData(5);
                                airObj.June_R = planRate.ConvertToBinaryData(6);
                                airObj.July_R = planRate.ConvertToBinaryData(7);
                                airObj.August_R = planRate.ConvertToBinaryData(8);
                                airObj.September_R = planRate.ConvertToBinaryData(9);
                                airObj.October_R = planRate.ConvertToBinaryData(10);
                                airObj.November_R = planRate.ConvertToBinaryData(11);
                                airObj.December_R = planRate.ConvertToBinaryData(12);
                            }


                            //将数据转换器内的数据更新
                            planAI.Create(dtStart, dtEnd, DayOfWeek, iInv, State,
                                Min, Max, AdvanceHour, string.Empty, string.Empty);

                            //更新实体类对象
                            airObj.PlanCode = key;
                            airObj.RoomCode = strRoomCode;
                            airObj.Property_id = PID;
                            airObj.Year = planAI.Year;
                            airObj.Level = "L";

                            airObj.Source = "DEFAULT";

                            #region 数据转换

                            //房型房量数据转换
                            airObj.January_AI = planAI.ConvertToBinaryData(1);
                            airObj.February_AI = planAI.ConvertToBinaryData(2);
                            airObj.March_AI = planAI.ConvertToBinaryData(3);
                            airObj.April_AI = planAI.ConvertToBinaryData(4);
                            airObj.May_AI = planAI.ConvertToBinaryData(5);
                            airObj.June_AI = planAI.ConvertToBinaryData(6);
                            airObj.July_AI = planAI.ConvertToBinaryData(7);
                            airObj.August_AI = planAI.ConvertToBinaryData(8);
                            airObj.September_AI = planAI.ConvertToBinaryData(9);
                            airObj.October_AI = planAI.ConvertToBinaryData(10);
                            airObj.November_AI = planAI.ConvertToBinaryData(11);
                            airObj.December_AI = planAI.ConvertToBinaryData(12);



                            #endregion

                            //写入数据库
                            if (!bll.insertorupdate(airObj))
                                return false;

                            #endregion

                            #region 记录到InventoryPlan表

                            shadow.ConnectionName = "mainDB";

                            invObj.CrateDate = DateTime.Now;

                            invObj.StartDate = dtStartDate;
                            invObj.EndDate = EndDate;

                            invObj.PID = PID;
                            invObj.PlanCode = key;
                            invObj.RoomCode = strRoomCode;

                            invObj.State = State;
                            invObj.Min = Min;
                            invObj.Max = Max;
                            invObj.AdvanceHour = AdvanceHour;

                            string strWeekString = "";

                            foreach (int day in DayOfWeek)
                                strWeekString += day.ToString() + ",";

                            strWeekString = strWeekString.TrimEnd(',');

                            invObj.RoomInventory = Inventory;
                            invObj.PlanQuota = int.Parse(Quota[key].ToString());
                            invObj.QuotaUnit = true; //百分比
                            invObj.RoomLevel = true;
                            invObj.WeekString = strWeekString;

                            b = shadow.Save();
                            
                            if (!b) return false;

                            #endregion

                            
                        }
                    }

                    #endregion


                }

                #endregion

                StartDate = StartDate.AddYears(1);

            }

            return true;
        }


        /// <summary>
        /// 计划级
        /// </summary>
        /// <param name="PID"></param>
        /// <param name="RatePlans"></param>
        /// <param name="Rate1"></param>
        /// <param name="Rate2"></param>
        /// <param name="Rate3"></param>
        /// <param name="Rate4"></param>
        /// <param name="Bed"></param>
        /// <param name="BF">含早</param>
        /// <param name="BFRate"></param>
        /// <param name="BFNum"></param>
        /// <param name="Inventory"></param>
        /// <param name="Min">最小入住天数</param>
        /// <param name="Max">最长入住天数</param>
        /// <param name="AdvanceHounr"></param>
        /// <param name="State"></param>
        /// <param name="Gua"></param>
        /// <param name="Cxl"></param>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        /// <param name="DayOfWeek"></param>
        /// <returns></returns>
        public  bool SavePlanLevel(int PID, string [] RatePlans, float Rate1, float Rate2, float Rate3, float Rate4, float Bed, 
            bool BF, float BFRate, int BFNum, int Inventory,int Min, int Max, int AdvanceHounr, string State, string Gua, string Cxl,

            DateTime StartDate, DateTime EndDate, int[] DayOfWeek, string Operator)
        {

            if (StartDate > EndDate) return false;

            DateTime dtStartDate = Convert.ToDateTime(StartDate.ToString()); //创建一个原始开始日期

            BllHCRS_AIR bll = new BllHCRS_AIR();

            int iYears = EndDate.Year - StartDate.Year;

            for (int i = 0; i <= iYears; i++)
            {

                #region 按年分隔日期

                DateTime dtStart = StartDate;
                DateTime dtEnd;

                if (iYears == 0)
                {
                    //同一年
                    dtEnd = EndDate;
                }
                else if (iYears == i)
                {
                    //最后一年

                    if (iYears >= 1)
                        dtStart = Convert.ToDateTime(dtStart.Year.ToString() + "-1-1");

                    dtEnd = EndDate;
                }
                else
                {
                    if (i > 0)
                        dtStart = Convert.ToDateTime(dtStart.Year.ToString() + "-1-1");

                    //设置成本年最后一天
                    dtEnd = Convert.ToDateTime(StartDate.AddYears(1).Year.ToString() + "-1-1").AddDays(-1);
                }

                #endregion

                #region 计划循环

                foreach (string rateplan in RatePlans)
                {

                    HotelAIProvider ai = new HotelAIProvider();
                    HotelRateProvider hotelrate = new HotelRateProvider();

                    string[] s = rateplan.Split('-');

                    if (s.Length != 2)
                    {
                        break;
                    }

                    //先从数据库读取对象

                    HCRS_AIR air;

                    string strWhere = "property_id =" + PID.ToString() + " AND level = 'L' AND RoomCode = '"
                        + s[0] + "' AND PlanCode = '" + s[1] + "' AND Year = " + StartDate.Year.ToString();

                    List<HCRS_AIR> airData = bll.getall(strWhere);

                    if (airData.Count > 0)
                    {
                        air = airData[0];

                        //为转换器加载数据
                        ai.Load(air);
                        hotelrate.Load(air);

                    }
                    else
                        air = new HCRS_AIR();

                    //将数据转换器内的数据更新
                    ai.Create(dtStart, dtEnd, DayOfWeek, Inventory, State,
                        Min, Max, AdvanceHounr,
                        Gua, Cxl);

                    hotelrate.Create(dtStart, dtEnd, DayOfWeek,
                        Rate1, Rate2, Rate3, Rate4, Bed,
                        BF, BFNum, BFRate);


                    //更新实体类对象
                    air.PlanCode = s[1];
                    air.RoomCode = s[0];
                    air.Property_id = PID;
                    air.Year = ai.Year;
                    air.Level = "L";

                    air.Source = "";

                    #region 数据转换

                    //房型房量数据转换
                    air.January_AI = ai.ConvertToBinaryData(1);
                    air.February_AI = ai.ConvertToBinaryData(2);
                    air.March_AI = ai.ConvertToBinaryData(3);
                    air.April_AI = ai.ConvertToBinaryData(4);
                    air.May_AI = ai.ConvertToBinaryData(5);
                    air.June_AI = ai.ConvertToBinaryData(6);
                    air.July_AI = ai.ConvertToBinaryData(7);
                    air.August_AI = ai.ConvertToBinaryData(8);
                    air.September_AI = ai.ConvertToBinaryData(9);
                    air.October_AI = ai.ConvertToBinaryData(10);
                    air.November_AI = ai.ConvertToBinaryData(11);
                    air.December_AI = ai.ConvertToBinaryData(12);


                    //价格数据转换
                    air.January_R = hotelrate.ConvertToBinaryData(1);
                    air.February_R = hotelrate.ConvertToBinaryData(2);
                    air.March_R = hotelrate.ConvertToBinaryData(3);
                    air.April_R = hotelrate.ConvertToBinaryData(4);
                    air.May_R = hotelrate.ConvertToBinaryData(5);
                    air.June_R = hotelrate.ConvertToBinaryData(6);
                    air.July_R = hotelrate.ConvertToBinaryData(7);
                    air.August_R = hotelrate.ConvertToBinaryData(8);
                    air.September_R = hotelrate.ConvertToBinaryData(9);
                    air.October_R = hotelrate.ConvertToBinaryData(10);
                    air.November_R = hotelrate.ConvertToBinaryData(11);
                    air.December_R = hotelrate.ConvertToBinaryData(12);


                    #endregion

                    //写入数据库
                    bool b = bll.insertorupdate(air);

                    if (!b)
                        return false;


                    #region 写入InventoryPlan...

                    HCRS_InventoryPlan invObj = new HCRS_InventoryPlan(); //房量配额设定记录表实体
                    Shadow<HCRS_InventoryPlan> shadow = new Shadow<HCRS_InventoryPlan>(invObj); //ORM对象

                    shadow.ConnectionName = "mainDB";

                    invObj.CrateDate = DateTime.Now;

                    invObj.StartDate = dtStartDate;
                    invObj.EndDate = EndDate;

                    invObj.PID = PID;
                    invObj.PlanCode = s[1];
                    invObj.RoomCode = s[0];

                    invObj.State = State;
                    invObj.Min = Min;
                    invObj.Max = Max;
                    invObj.AdvanceHour = AdvanceHounr;

                    invObj.RoomInventory = Inventory;
                    invObj.PlanQuota = Inventory;

                    string strWeekString = "";

                    foreach (int day in DayOfWeek)
                        strWeekString += day.ToString() + ",";

                    strWeekString = strWeekString.TrimEnd(',');

                    invObj.WeekString = strWeekString;
                    invObj.QuotaUnit = false; //数值
                    invObj.RoomLevel = false;

                    invObj.Gua = Gua;
                    invObj.Cxl = Cxl;

                    invObj.Rate1 = Rate1;
                    invObj.Rate2 = Rate2;
                    invObj.Rate3 = Rate3;
                    invObj.Rate4 = Rate4;

                    invObj.Bed = Bed;
                    invObj.BreakfastNum = BFNum;
                    invObj.BreakfastRate = BFRate;
                    invObj.HasBreakfast = BF;

                    b = shadow.Save();

                    if (!b)
                        return false;

                    #endregion

                    
                }

                #endregion

                StartDate = StartDate.AddYears(1);

            }

            //记录到操作日志air_log

            return AddAirLog(PID, RatePlans, Rate1, Rate2, Rate3, Rate4, Bed, BF, BFRate, BFNum, Inventory, Min, Max, AdvanceHounr, State,
                Gua, Cxl, dtStartDate, EndDate, DayOfWeek, Operator);

        }

        /// <summary>
        /// 归还房量
        /// </summary>
        /// <param name="pId">酒店id</param>
        /// <param name="roomCode">房型代码</param>
        /// <param name="planCode">价格代码</param>
        /// <param name="roomDateRoom">日期和房间数 形如 List《["2008-02-01","5"]》</param>
        /// <returns></returns>
        public bool ReturnRoom(int pId, string roomCode, string rateCode,List<string[]> roomDateRoom)
        {
            #region 收集数据

            Dictionary<int, int> dicYearIndex = new Dictionary<int, int>();

            DataTable dtYearGroup = new DataTable(); //用于按年分类的日期

            dtYearGroup.Columns.Add("Year", typeof(int));
            dtYearGroup.Columns.Add("Day", typeof(DateTime));
            dtYearGroup.Columns.Add("Inv", typeof(int));

            //收集分类数据
            foreach (string[] strValue in roomDateRoom)
            {
                if (strValue.Length >= 2)
                {

                    DateTime date;

                    DateTime.TryParse(strValue[0], out date);

                    int iInv = 0;
                    int.TryParse(strValue[1], out iInv);

                    DataRow dr = dtYearGroup.NewRow();

                    dr[0] = date.Year;
                    dr[1] = date;
                    dr[3] = iInv;

                    dtYearGroup.Rows.Add(dr);

                    if (!dicYearIndex.ContainsKey(date.Year))
                        dicYearIndex[date.Year] = 1;
                    else
                        dicYearIndex[date.Year] += 1;
                    
                }

            }

            #endregion

            #region 更新数据

            //按年份取出数据
            BllHCRS_AIR bll = new BllHCRS_AIR();

            foreach (int iYear in dicYearIndex.Keys)
            {
 
                //从数据库获取一年的AIR信息

                string strWhere = "property_id =" + pId.ToString() + " AND level = 'R' AND RoomCode = '" + roomCode + "' AND Year = " + iYear.ToString();

                List<HCRS_AIR> airData = bll.getall(strWhere);  //获取房型级数据

                strWhere = "property_id =" + pId.ToString() + " AND level = 'L' AND RoomCode = '" + roomCode + 
                    "' AND PlanCode = '" + rateCode + "' AND Year = " + iYear.ToString();

                List<HCRS_AIR> airPlanData = bll.getall(strWhere); //获取计划级数据


                
                HCRS_AIR air, airPlan;

                if (airData.Count > 0)
                    air = airData[0];
                else
                    air = new HCRS_AIR();

                if (airPlanData.Count > 0)
                    airPlan = airPlanData[0];
                else
                    airPlan = new HCRS_AIR();

                HotelAIProvider ai = new HotelAIProvider();      //房型级适配器
                HotelAIProvider aiPlan = new HotelAIProvider();  //计划级适配器

                //为AI适配器加载数据
                ai.Load(air);    
                aiPlan.Load(airPlan);

                DataRow[] drDate = dtYearGroup.Select("Year = " + iYear.ToString());

                //修改日AI数据
                foreach (DataRow dr in drDate)
                {
                    DateTime dtDay = DateTime.Parse(dr[1].ToString());
                    int iInv = int.Parse(dr[2].ToString());

                    ai.Create(dtDay, iInv);
                    aiPlan.Create(dtDay, iInv);
                }

                //保存该年的数据

                //房型级
                air.PlanCode = string.Empty;
                air.RoomCode = roomCode;
                air.Property_id = pId;
                air.Year = ai.Year;
                air.Level = "R";
                air.Source = "DEFAULT";

                //计划级
                airPlan.PlanCode = rateCode;
                airPlan.RoomCode = roomCode;
                airPlan.Property_id = pId;
                airPlan.Year = ai.Year;
                airPlan.Level = "L";
                airPlan.Source = "DEFAULT";

                #region 数据转换

                //房型级房量数据转换
                air.January_AI = ai.ConvertToBinaryData(1);
                air.February_AI = ai.ConvertToBinaryData(2);
                air.March_AI = ai.ConvertToBinaryData(3);
                air.April_AI = ai.ConvertToBinaryData(4);
                air.May_AI = ai.ConvertToBinaryData(5);
                air.June_AI = ai.ConvertToBinaryData(6);
                air.July_AI = ai.ConvertToBinaryData(7);
                air.August_AI = ai.ConvertToBinaryData(8);
                air.September_AI = ai.ConvertToBinaryData(9);
                air.October_AI = ai.ConvertToBinaryData(10);
                air.November_AI = ai.ConvertToBinaryData(11);
                air.December_AI = ai.ConvertToBinaryData(12);

                byte[] bEmpty = new byte[1];

                air.January_R = bEmpty;
                air.February_R = bEmpty;
                air.March_R = bEmpty;
                air.April_R = bEmpty;
                air.May_R = bEmpty;
                air.June_R = bEmpty;
                air.July_R = bEmpty;
                air.August_R = bEmpty;
                air.September_R = bEmpty;
                air.October_R = bEmpty;
                air.November_R = bEmpty;
                air.December_R = bEmpty;

                //房型级房量数据转换
                airPlan.January_AI = aiPlan.ConvertToBinaryData(1);
                airPlan.February_AI = aiPlan.ConvertToBinaryData(2);
                airPlan.March_AI = aiPlan.ConvertToBinaryData(3);
                airPlan.April_AI = aiPlan.ConvertToBinaryData(4);
                airPlan.May_AI = aiPlan.ConvertToBinaryData(5);
                airPlan.June_AI = aiPlan.ConvertToBinaryData(6);
                airPlan.July_AI = aiPlan.ConvertToBinaryData(7);
                airPlan.August_AI = aiPlan.ConvertToBinaryData(8);
                airPlan.September_AI = aiPlan.ConvertToBinaryData(9);
                airPlan.October_AI = aiPlan.ConvertToBinaryData(10);
                airPlan.November_AI = aiPlan.ConvertToBinaryData(11);
                airPlan.December_AI = aiPlan.ConvertToBinaryData(12);

                airPlan.January_R = bEmpty;
                airPlan.February_R = bEmpty;
                airPlan.March_R = bEmpty;
                airPlan.April_R = bEmpty;
                airPlan.May_R = bEmpty;
                airPlan.June_R = bEmpty;
                airPlan.July_R = bEmpty;
                airPlan.August_R = bEmpty;
                airPlan.September_R = bEmpty;
                airPlan.October_R = bEmpty;
                airPlan.November_R = bEmpty;
                airPlan.December_R = bEmpty;

                #endregion

                //写入数据库
                bll.insertorupdate(air);     //房型级
                bll.insertorupdate(airPlan); //计划级
            }

            #endregion

            return true;
        }

        public bool ApplyPlan(HCRS_InventoryPlan InvPlan)
        {

            DateTime dtStartDate = Convert.ToDateTime(InvPlan.StartDate.ToString()); //创建一个原始开始日期

            BllHCRS_AIR bll = new BllHCRS_AIR();

            int iYears = InvPlan.EndDate.Year - InvPlan.StartDate.Year;


            int[] iWeek = new int[7];

            for (int i = 0; i < iWeek.Length; i++) iWeek[i] = 0;

            if (!string.IsNullOrEmpty(InvPlan.WeekString))
            {
                string[] str = InvPlan.WeekString.Split(',');

                foreach (string s in str)
                    iWeek[int.Parse(s) - 1] = 1;
            }

            for (int i = 0; i <= iYears; i++)
            {

                #region 按年分隔日期

                DateTime dtStart = InvPlan.StartDate;
                DateTime dtEnd;

                if (iYears == 0)
                {
                    //同一年
                    dtEnd = InvPlan.EndDate;
                }
                else if (iYears == i)
                {
                    //最后一年

                    if (iYears >= 1)
                        dtStart = Convert.ToDateTime(dtStart.Year.ToString() + "-1-1");

                    dtEnd = InvPlan.EndDate;
                }
                else
                {
                    if (i > 0)
                        dtStart = Convert.ToDateTime(dtStart.Year.ToString() + "-1-1");

                    //设置成本年最后一天
                    dtEnd = Convert.ToDateTime(InvPlan.StartDate.AddYears(1).Year.ToString() + "-1-1").AddDays(-1);
                }

                #endregion


                HotelAIProvider ai = new HotelAIProvider();

                HotelRateProvider hotelrate = new HotelRateProvider();

                //先从数据库读取L级别

                HCRS_AIR air;

                List<HCRS_AIR> airData = getPlanLevelAIR(InvPlan.PID, InvPlan.RoomCode,InvPlan.PlanCode, InvPlan.StartDate.Year);

                if (airData.Count > 0)
                {
                    air = airData[0];

                    //为转换器加载数据

                    ai.Load(air);
                    hotelrate.Load(air);
                }
                else
                {
                    air = new HCRS_AIR();

                    hotelrate.Create(dtStart, dtEnd, iWeek, InvPlan.Rate1, InvPlan.Rate2, InvPlan.Rate3, InvPlan.Rate4, InvPlan.Bed, 
                        InvPlan.HasBreakfast, InvPlan.BreakfastNum, InvPlan.BreakfastRate);

                    air.January_R = hotelrate.ConvertToBinaryData(1);
                    air.February_R = hotelrate.ConvertToBinaryData(2);
                    air.March_R = hotelrate.ConvertToBinaryData(3);
                    air.April_R = hotelrate.ConvertToBinaryData(4);
                    air.May_R = hotelrate.ConvertToBinaryData(5);
                    air.June_R = hotelrate.ConvertToBinaryData(6);
                    air.July_R = hotelrate.ConvertToBinaryData(7);
                    air.August_R = hotelrate.ConvertToBinaryData(8);
                    air.September_R = hotelrate.ConvertToBinaryData(9);
                    air.October_R = hotelrate.ConvertToBinaryData(10);
                    air.November_R = hotelrate.ConvertToBinaryData(11);
                    air.December_R = hotelrate.ConvertToBinaryData(12);
                }

                int iInv = 0;

                if (InvPlan.QuotaUnit)
                {
                    double fInv = InvPlan.RoomInventory * double.Parse(InvPlan.PlanQuota.ToString()) * .01;
                    iInv = (int)fInv;
                }
                else
                    iInv = InvPlan.PlanQuota;

                if (iInv > 0)
                {
                    //将数据转换器内的数据更新
                    ai.Create(dtStart, dtEnd, iWeek, iInv, InvPlan.State,
                        InvPlan.Min, InvPlan.Max, InvPlan.AdvanceHour, InvPlan.Gua, InvPlan.Cxl);

                    //更新实体类对象
                    air.PlanCode = InvPlan.PlanCode;
                    air.RoomCode = InvPlan.RoomCode;
                    air.Property_id = InvPlan.PID;
                    air.Year = ai.Year;
                    air.Level = "L";

                    air.Source = "DEFAULT";

                    #region 数据转换

                    //房型房量数据转换
                    air.January_AI = ai.ConvertToBinaryData(1);
                    air.February_AI = ai.ConvertToBinaryData(2);
                    air.March_AI = ai.ConvertToBinaryData(3);
                    air.April_AI = ai.ConvertToBinaryData(4);
                    air.May_AI = ai.ConvertToBinaryData(5);
                    air.June_AI = ai.ConvertToBinaryData(6);
                    air.July_AI = ai.ConvertToBinaryData(7);
                    air.August_AI = ai.ConvertToBinaryData(8);
                    air.September_AI = ai.ConvertToBinaryData(9);
                    air.October_AI = ai.ConvertToBinaryData(10);
                    air.November_AI = ai.ConvertToBinaryData(11);
                    air.December_AI = ai.ConvertToBinaryData(12);

                    #endregion

                    //写入数据库
                    bool b = bll.insertorupdate(air);

                    if (!b)
                        return false;

                }

                InvPlan.StartDate = InvPlan.StartDate.AddYears(1);

            }

            return true;
        }

        /// <summary>
        /// 记录操作记录
        /// </summary>
        /// <param name="PID"></param>
        /// <param name="RatePlans"></param>
        /// <param name="Rate1"></param>
        /// <param name="Rate2"></param>
        /// <param name="Rate3"></param>
        /// <param name="Rate4"></param>
        /// <param name="Bed"></param>
        /// <param name="BF"></param>
        /// <param name="BFRate"></param>
        /// <param name="BFNum"></param>
        /// <param name="Inventory"></param>
        /// <param name="Min"></param>
        /// <param name="Max"></param>
        /// <param name="AdvanceHounr"></param>
        /// <param name="State"></param>
        /// <param name="Gua"></param>
        /// <param name="Cxl"></param>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        /// <param name="DayOfWeek"></param>
        /// <param name="Operator"></param>
        /// <returns></returns>
        public bool AddAirLog(int PID, string[] RatePlans, float Rate1, float Rate2, float Rate3, float Rate4, float Bed,
            bool BF, float BFRate, int BFNum, int Inventory, int Min, int Max, int AdvanceHounr, string State, string Gua, string Cxl,
            DateTime StartDate, DateTime EndDate, int[] DayOfWeek, string Operator)
        {

            #region 写入Air Log...

            AIR_Log logObj = new AIR_Log();

            Shadow<AIR_Log> shadow = new Shadow<AIR_Log>(logObj);

            shadow.ConnectionName = MainBase.CONNECTION_STRING;

            logObj.CrateDate = DateTime.Now;

            logObj.StartDate = StartDate;
            logObj.EndDate = EndDate;

            logObj.PID = PID;

            logObj.State = State;
            logObj.Min = Min;
            logObj.Max = Max;
            logObj.AdvanceHour = AdvanceHounr;

            logObj.RoomInventory = Inventory;

            string strWeekString = "";

            foreach (int day in DayOfWeek)
                strWeekString += day.ToString() + ",";

            strWeekString = strWeekString.TrimEnd(',');

            logObj.WeekString = strWeekString;

            logObj.Gua = Gua;
            logObj.Cxl = Cxl;

            logObj.Rate1 = Rate1;
            logObj.Rate2 = Rate2;
            logObj.Rate3 = Rate3;
            logObj.Rate4 = Rate4;

            logObj.Bed = Bed;
            logObj.BreakfastNum = BFNum;
            logObj.BreakfastRate = BFRate;
            logObj.HasBreakfast = BF;

            logObj.PlanLevel = "L";
            logObj.Operator = Operator;

            shadow.Save();

            int iLogID = logObj.ID;

            #endregion

            #region 写入Air Log Code

            foreach (string plan in RatePlans)
            {
                string [] str = plan.Split('-');

                string strRoomCode = str[0];
                string strPlanCode = str[1];

                AIR_LOG_CODE code = new AIR_LOG_CODE();

                Shadow<AIR_LOG_CODE> logSha = new Shadow<AIR_LOG_CODE>(code);
                logSha.ConnectionName = MainBase.CONNECTION_STRING;

                code.LogID = iLogID;
                code.PlanCode = strPlanCode;
                code.RoomCode = strRoomCode;

                logSha.Save();
                
            }

            #endregion

            return true;
        }

        /// <summary>
        /// 查找操作AIR日志
        /// </summary>
        /// <param name="PID"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="RecordCount"></param>
        /// <param name="PageCount"></param>
        /// <returns></returns>
        public List<AIR_Log> GetAirLogPID(int PID, int PageIndex, int PageSize, string Query, out int RecordCount, out int PageCount)
        {

            ShadowSearch<AIR_Log> search = new ShadowSearch<AIR_Log>();
            search.ConnectionName = MainBase.CONNECTION_STRING;

            ShadowRule rule = new ShadowRule();

            rule.PageSize = PageSize;
            rule.PageIndex = PageIndex;

            rule.OrderString = "ID DESC";

            List<AIR_Log> lst = search.Search("PID = " + PID.ToString(), rule);

            RecordCount = rule.RecordCount;
            PageCount = rule.PageCount;

            return lst;
        }


        public AIR_Log GetLogByID(int ID)
        {
            ShadowSearch<AIR_Log> search = new ShadowSearch<AIR_Log>();
            search.ConnectionName = MainBase.CONNECTION_STRING;

            List<AIR_Log> lst = search.Search("ID = " + ID.ToString());

            if (lst.Count > 0)

                return lst[0];
            else
                return null;
        }

        public List<AIR_LOG_CODE> GetLogCodeListByLogID(int LogID)
        {
            ShadowSearch<AIR_LOG_CODE> search = new ShadowSearch<AIR_LOG_CODE>();
            search.ConnectionName = MainBase.CONNECTION_STRING;

            List<AIR_LOG_CODE> lst = search.Search("LOG_ID = " + LogID.ToString() + " ORDER BY RoomCode");

            return lst;

        }


        public enum AIRLevel { L, P, R }


        public DataTable SearchAIR(int PID, DateTime StartDate, DateTime EndDate, AIRLevel Lev, string RoomCode)
        {

            BllHCRS_AIR bll = new BllHCRS_AIR();

            string strWhere = "property_id =" + PID.ToString() + 
                " AND level = '" + Lev.ToString() + "'" + 
                " AND Year IN(" + StartDate.Year.ToString() + "," + EndDate.Year.ToString() + ")";

            if (!string.IsNullOrEmpty(RoomCode))
            {
                strWhere += " AND RoomCode = '" + RoomCode + "'";
            }

            List<HCRS_AIR> lst = bll.getall(strWhere);

            return ConvertToTable(lst, StartDate, EndDate);

        }


        private DataTable ConvertToTable(List<HCRS_AIR> AirList, DateTime StartDate, DateTime EndDate)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("RoomCode");
            dt.Columns.Add("RateCode");
            dt.Columns.Add("RoomInv", System.Type.GetType("System.Int32"));
            dt.Columns.Add("Rate1", System.Type.GetType("System.Single"));
            dt.Columns.Add("Rate2", System.Type.GetType("System.Single"));
            dt.Columns.Add("Rate3", System.Type.GetType("System.Single"));
            dt.Columns.Add("Rate4", System.Type.GetType("System.Single"));
            dt.Columns.Add("BF", System.Type.GetType("System.Boolean"));

            HotelRateProvider provider = new HotelRateProvider();
            HotelAIProvider ai = new HotelAIProvider();

            int iYear = 0;
            int iMonth = 0;
            int iEndMonth = 12;


            for (int i = StartDate.Year; i <= EndDate.Year; i++)
            {
                if (i == StartDate.Year)
                    iMonth = StartDate.Month;
                else
                    iMonth = 1;

                if (i == EndDate.Year)
                    iEndMonth = EndDate.Month;
                else
                    iEndMonth = 12;

                if (AirList == null)
                    break;

                foreach (HCRS_AIR air in AirList)
                {
                    if (air.Year == i)
                    {
                        provider.Load(air);
                        ai.Load(air);

                        for (int m = iMonth; m <= iEndMonth; m++)
                        {
                            
                            DataSet ds = null;
                            DataSet dsAI = null;

                            #region 获取每月数据，筛选天数

                            switch (m)
                            {
                                case 1:
                                    ds = provider.January;
                                    dsAI = ai.January;
                                    break;
                                case 2:
                                    ds = provider.February;
                                    dsAI = ai.February;
                                    break;
                                case 3:
                                    ds = provider.March;
                                    dsAI = provider.March;
                                    break;
                                case 4:
                                    ds = provider.April;
                                    dsAI = ai.April;
                                    break;
                                case 5:
                                    ds = provider.May;
                                    dsAI = ai.May;
                                    break;
                                case 6:
                                    ds = provider.June;
                                    dsAI = ai.May;
                                    break;
                                case 7:
                                    ds = provider.July;
                                    dsAI = ai.July;
                                    break;
                                case 8:
                                    ds = provider.August;
                                    dsAI = ai.August;
                                    break;
                                case 9:
                                    ds = provider.September;
                                    dsAI = ai.September;
                                    break;
                                case 10:
                                    ds = provider.October;
                                    dsAI = ai.October;
                                    break;
                                case 11:
                                    ds = provider.November;
                                    dsAI = ai.November;
                                    break;
                                case 12:
                                    ds = provider.December;
                                    dsAI = ai.December;
                                    break;

                            }

                            #endregion

                            if (ds != null && ds.Tables.Count > 0)
                            {
                                DataRow[] drs = ds.Tables[0].Select(string.Format("Date >= '{0}' AND Date <= '{1}'", StartDate, EndDate));

                                foreach (DataRow dr in drs)
                                {

                                    DataRow[] drSearch = dt.Select(string.Format("RoomCode = '{0}' AND RateCode = '{1}' AND Rate1 = {2} AND Rate2 = {3} AND Rate3 = {4} AND Rate4 = {5} AND BF = {6}", 
                                        air.RoomCode, air.PlanCode, dr["Rate1"], dr["Rate2"],dr["Rate3"],dr["Rate4"], dr["BF"]));

                                    if (drSearch.Length == 0)
                                    {
                                        DataRow r = dt.NewRow();

                                        int iInv = 0;

                                        //get AI
                                        if (dsAI != null && dsAI.Tables.Count > 0)
                                        {
                                            DataRow[] airow = dsAI.Tables[0].Select(string.Format("Date = '{0}'", dr["Date"]));

                                            if (airow.Length > 0)
                                            {
                                                int.TryParse(airow[0]["Inventory"].ToString(), out iInv);
                                            }
                                        }

                                        r["RoomInv"] = iInv;

                                        r["RoomCode"] = air.RoomCode;
                                        r["RateCode"] = air.PlanCode;

                                        r["Rate1"] = dr["Rate1"];
                                        r["Rate2"] = dr["Rate2"];
                                        r["Rate3"] = dr["Rate3"];
                                        r["Rate4"] = dr["Rate4"];
                                        r["BF"] = dr["BF"];

                                        dt.Rows.Add(r);
                                    }

                                }
                            }


                        }
                    }
                }
            }
            
            return dt;

        }
    }
}
